package homework1.server;

import homework1.common.Message;
import homework1.utils.Tool;

import java.io.*;
import java.net.Socket;

/**
 * 该类的对象与客户端保持一一通信
 *
 * @author jian
 * @date 2024/01/08 19:29
 **/
public class ServerConnectClientThread extends Thread {


    private Socket socket;
    private String Id;//连接到服务端的用户id

    public ServerConnectClientThread(Socket socket, String Id) {
        this.socket = socket;
        this.Id = Id;
    }


    @Override
    public void run() {
        try {
            while (true){
                ObjectInputStream ois =
                        new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();

                // 根据文件类型处理文件
                if ("xml".equals(message.getContentType())) {
                    // 接收XML数据并保存到文件
                    Tool.saveToFile(Tool.decryptFileContent(message.getFileBytes()), Server.dirPath + "temp.xml");
                    System.out.println("XML文件保存成功!");
                    System.out.println("输入命令以查看文件：");
                } else if ("json".equals(message.getContentType())) {
                    // 接收JSON数据并保存到文件
                    Tool.saveToFile(Tool.decryptFileContent(message.getFileBytes()), Server.dirPath + "temp.json");
                    System.out.println("JSON文件保存成功!");
                    System.out.println("输入命令以查看文件：");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public Socket getSocket(){
        return socket;
    }
    


}
